package com.weixing.mall.provider.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.core.enums.OrderSysTagEnum;
import com.weixing.mall.provider.api.model.enums.AgentLevelEnum;
import com.weixing.mall.provider.api.model.vo.dto.DepotRPcVo;
import com.weixing.mall.provider.api.service.DepotServiceRpc;
import com.weixing.mall.provider.mapper.DayReportStorageMapper;
import com.weixing.mall.provider.model.domain.Order;
import com.weixing.mall.provider.model.enums.AfterSaleResultEnum;
import com.weixing.mall.provider.model.enums.AfterSalesTypeEnum;
import com.weixing.mall.provider.model.enums.OrderFrontStateEnum;
import com.weixing.mall.provider.model.enums.OrderLogTypeEnum;
import com.weixing.mall.provider.model.vo.report.ActivityVo;
import com.weixing.mall.provider.model.vo.report.storage.*;
import com.weixing.mall.provider.service.IDayReportStorageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author jzy
 * @date 2020/6/5
 */
@Service
public class DayReportStorageServiceImpl extends ServiceImpl<DayReportStorageMapper, Order> implements IDayReportStorageService {
    @Autowired
    private DepotServiceRpc depotServiceRpc;

    @Override
    public IPage<StorageInAndOutDepotSummaryVo> storageInAndOutDepotSummary(Long shipper,Long depotId,String yearMonth, String startTime, String endTime, String sortField, String sortType, Page page) {
        return baseMapper.storageInAndOutDepotSummary(page,shipper,depotId,yearMonth,startTime,endTime,sortField,sortType);
    }

    @Override
    public IPage<StorageInDepotDetailVo> storageInDepotDetail(Integer type, Long shipper,Long depotId,String yearMonth, String startTime, String endTime, String sortField, String sortType, Page page) {
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("date_format(bill.created_time,'%Y-%m') month,bill.in_depot_type type,sum(product.quantity) quantity,sum(product.quantity*goods.discount_price) amount,sum(product.quantity*goods.cost_price) amountCost");
        q.eq("bill.is_finish",1);//审核完成的
        q.eq(type!=null,"bill.in_depot_type",type);
        q.eq(shipper!=null,"bill.created_by",shipper);
        q.eq(depotId!=null,"bill.input_depot",depotId);
        q.ge(StrUtil.isNotEmpty(startTime),"date_format(bill.created_time,'%Y-%m-%d')",startTime);
        q.le(StrUtil.isNotEmpty(endTime),"date_format(bill.created_time,'%Y-%m-%d')",endTime);
        q.eq(StrUtil.isNotEmpty(yearMonth),"date_format(bill.created_time,'%Y-%m')",yearMonth);
        //排序
        q.orderBy(StrUtil.isNotEmpty(sortField), StringUtils.equalsIgnoreCase("ASC", sortType),sortField);
        //默认时间正序
        q.orderByAsc(StrUtil.isEmpty(sortField), "bill.created_time");
        q.groupBy("date_format(bill.created_time,'%Y-%m')","bill.in_depot_type");
        return baseMapper.storageInDepotDetail(page,q);
    }

    @Override
    public IPage<StorageOutDepotDetailVo> storageOutDepotDetail(Integer type, Long shipper,Long depotId,String yearMonth, String startTime, String endTime, String sortField, String sortType, Page page) {
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("date_format(bill.created_time,'%Y-%m') month,bill.out_depot_type type,sum(product.quantity) quantity,sum(product.quantity*goods.discount_price) amount,sum(product.quantity*goods.cost_price) amountCost");
        q.eq("bill.is_finish",1);//审核完成的
        q.eq(type!=null,"bill.out_depot_type",type);
        q.eq(shipper!=null,"bill.created_by",shipper);
        q.eq(depotId!=null,"bill.output_depot",depotId);
        q.ge(StrUtil.isNotEmpty(startTime),"date_format(bill.created_time,'%Y-%m-%d')",startTime);
        q.le(StrUtil.isNotEmpty(endTime),"date_format(bill.created_time,'%Y-%m-%d')",endTime);
        q.eq(StrUtil.isNotEmpty(yearMonth),"date_format(bill.created_time,'%Y-%m')",yearMonth);
        //排序
        q.orderBy(StrUtil.isNotEmpty(sortField), StringUtils.equalsIgnoreCase("ASC", sortType),sortField);
        q.groupBy("date_format(bill.created_time,'%Y-%m')","bill.out_depot_type");
        //默认时间正序
        q.orderByAsc(StrUtil.isEmpty(sortField), "bill.created_time");
        return baseMapper.storageOutDepotDetail(page,q);
    }

    @Override
    public IPage<StorageActivitySalesVo> activitySalesReport(String yearMonth, String startTime, String endTime, Long actId, String sortField, String sortType, Page page) {
        Long appId = null;
        Long erpId = null;
        Result<DepotRPcVo> appResult = depotServiceRpc.getBycode(GlobalConstant.DepotCode.APP);
        if (appResult.isSuccess()&& ObjectUtil.isNotEmpty(appResult.getData())){
            appId = appResult.getData().getId();
        }
        Result<DepotRPcVo> erpResult = depotServiceRpc.getBycode(GlobalConstant.DepotCode.ERP);
        if (erpResult.isSuccess()&& ObjectUtil.isNotEmpty(erpResult.getData())){
            erpId = erpResult.getData().getId();
        }
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("date_format(o.audit_time,'%Y-%m-%d') date" +
                ",count(if(o.depot_id="+ appId +",true,null)) appSaleQuantity" +
                ",sum(if(o.depot_id="+ appId +",o.order_price,0)) appSaleAmount" +
                ",count(if(o.depot_id="+ appId +" and o.sys_tag="+ OrderSysTagEnum.DHK_TAG_402.getValue() +",true,null)) appStockoutQuantity" +
                ",sum(if(o.depot_id="+ appId +" and o.sys_tag="+ OrderSysTagEnum.DHK_TAG_402.getValue() +",o.order_price,0)) appStockoutAmount" +
                ",count(if(o.depot_id="+ appId +" and o.sys_tag="+ OrderSysTagEnum.QXK_TAG_401.getValue() +",true,null)) appCancelQuantity" +
                ",sum(if(o.depot_id="+ appId +" and o.sys_tag="+ OrderSysTagEnum.QXK_TAG_401.getValue() +",o.order_price,0)) appCancelAmount" +
                ",count(if(o.depot_id="+ erpId +",true,null)) erpSaleQuantity" +
                ",sum(if(o.depot_id="+ erpId +",o.order_price,0)) erpSaleAmount" +
                ",count(if(o.depot_id="+ erpId +" and o.sys_tag="+ OrderSysTagEnum.DHK_TAG_402.getValue() +",true,null)) erpStockoutQuantity" +
                ",sum(if(o.depot_id="+ erpId +" and o.sys_tag="+ OrderSysTagEnum.DHK_TAG_402.getValue() +",o.order_price,0)) erpStockoutAmount" +
                ",count(IF(o.sys_tag = "+OrderSysTagEnum.YTHC_TAG_505.getValue()+",TRUE,NULL)) refundQuantity" +
                ",sum(IF(o.sys_tag = "+OrderSysTagEnum.YTHC_TAG_505.getValue()+",o.order_price,0)) refundAmount");
        q.eq(actId!=null,"o.act_id",actId);
        q.eq(StrUtil.isNotEmpty(yearMonth),"date_format(o.audit_time,'%Y-%m')",yearMonth);
        q.ge(StrUtil.isNotEmpty(startTime),"date_format(o.audit_time,'%Y-%m-%d')",startTime);
        q.le(StrUtil.isNotEmpty(endTime),"date_format(o.audit_time,'%Y-%m-%d')",endTime);
        //只筛选审核完成的订单
        q.isNotNull("o.audit_time");
        q.isNotNull("o.order_type");
        q.groupBy("date_format(o.audit_time,'%Y-%m-%d')");
        //排序
        q.orderBy(StrUtil.isNotEmpty(sortField), StringUtils.equalsIgnoreCase("DESC", sortType),sortField);
        //默认时间正序
        q.orderByAsc(StrUtil.isEmpty(sortField), "o.audit_time");
        return baseMapper.activitySalesReport(page, q);
    }

    @Override
    public IPage<StorageActivitySalesDetailVo> activitySalesReportDetail(Integer type,Integer itemStatus, String userName, String startTime, String endTime, Long actId, String depotCode, String sortField, String sortType, Page page) {
        Long appId = null;
        Long erpId = null;
        Result<DepotRPcVo> appResult = depotServiceRpc.getBycode(GlobalConstant.DepotCode.APP);
        if (appResult.isSuccess()&& ObjectUtil.isNotEmpty(appResult.getData())){
            appId = appResult.getData().getId();
        }
        Result<DepotRPcVo> erpResult = depotServiceRpc.getBycode(GlobalConstant.DepotCode.ERP);
        if (erpResult.isSuccess()&& ObjectUtil.isNotEmpty(erpResult.getData())){
            erpId = erpResult.getData().getId();
        }
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("o.order_sn orderSn,goods.goods_img goodsImg,goods.goods_name goodsName,goods.style_no styleNo,goods.partition_name partitionName,goods.goods_sn goodsSn,goods.sku_desp skuDesp,goods.color" +
                ",goods.size,o.depot_id depotId,o.depot_name depotName,o.order_status orderStatus,o.item_status itemStatus" +
                ",o.agent_id agentId,o.agent_name agentName,o.customer_id customerId,o.customer_name customerName,address.contact_user contactUser" +
                ",address.contact_phone contactPhone,CONCAT_WS('',address.province,address.city,address.region,address.town,address.addr_detail) address" +
                ",o.order_type orderType,o.audit_time,o.order_price orderPrice,o.order_price*o.discount discountPrice");
        q.eq(itemStatus!=null,"o.item_status",itemStatus);
        //APP仓库销售数量
        if (type!=null&&type==1){
            q.eq("o.depot_id",appId);
        }
        //APP仓断货数量
        if (type!=null&&type==2){
            q.eq("o.depot_id",appId);
            q.eq("o.sys_tag",OrderSysTagEnum.DHK_TAG_402.getValue() );
        }
        //APP仓取消数量
        if (type!=null&&type==3){
            q.eq("o.depot_id",appId);
            q.eq("o.sys_tag",OrderSysTagEnum.QXK_TAG_401.getValue());
        }
        //ERP仓销售数量
        if (type!=null&&type==4){
            q.eq("o.depot_id",erpId);
        }
        //ERP仓断货数量
        if (type!=null&&type==5){
            q.eq("o.depot_id",erpId);
            q.eq("o.sys_tag",OrderSysTagEnum.DHK_TAG_402.getValue() );
        }
        q.like(StrUtil.isNotEmpty(userName),"address.contact_user",userName);
        q.ge(StrUtil.isNotEmpty(startTime),"date_format(o.audit_time,'%Y-%m-%d')",startTime);
        q.le(StrUtil.isNotEmpty(endTime),"date_format(o.audit_time,'%Y-%m-%d')",endTime);
        //只筛选审核完成的订单
        q.isNotNull("o.audit_time");
        q.isNotNull("o.order_type");
        q.orderByDesc( "o.audit_time");
        return baseMapper.activitySalesReportDetail(page, q);
    }

    @Override
    public IPage<StorageDoSampleVo> storageDoAndSample(Integer type,Long depotId, String yearMonth, String startTime, String endTime, String sortField, String sortType, Page page) {
        return baseMapper.storageDoAndSample(page,type,depotId,yearMonth,startTime,endTime,sortField,sortType);
    }

    @Override
    public IPage<StorageExchangeReportVo> exchangeReport(Integer roleType, Long agentId, Integer role, String userName, String auditStartTime, String auditEndTime, String exchangeStartTime, String exchangeEndTime, Page page) {
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("o.buyer userName,o.order_sn orderSn,o.order_price orderPrice,o.id orderId" +
                ",case o.order_from when 1 then '客服' when 2 then '代理商' when 3 then '客户' else '' end userRole" +
                ",o.audit_time,o.created_time,1 AS quantity" +
                ",afterSale.audited_time exchangeTime" +
                ",afterSale.customer_remark remark,afterSale.id afterSaleId");
        q.eq(roleType!=null&&roleType==1,"o.customer_id",agentId);
        q.eq("afterSale.after_sale_type",AfterSalesTypeEnum.EXCHANE_GOODS.getValue());
        q.and(roleType!=null&&roleType==2,i->i.eq("o.agent_id",agentId).or().eq("o.distributor_id",agentId).or().eq("o.level1st",agentId).or().eq("o.level2nd",agentId).or().eq("o.level3rd",agentId).or().eq("o.level4th",agentId));
        q.like(StrUtil.isNotEmpty(userName),"o.buyer",userName);
        q.eq(role!=null,"o.order_from",role);
        q.ge(StrUtil.isNotEmpty(auditStartTime),"date_format(o.audit_time,'%Y-%m-%d')",auditStartTime);
        q.le(StrUtil.isNotEmpty(auditEndTime),"date_format(o.audit_time,'%Y-%m-%d')",auditEndTime);
        q.ge(StrUtil.isNotEmpty(exchangeStartTime),"date_format(o.audit_time,'%Y-%m-%d')",exchangeStartTime);
        q.le(StrUtil.isNotEmpty(exchangeEndTime),"date_format(o.audit_time,'%Y-%m-%d')",exchangeEndTime);
        //只筛选审核完成的订单
        q.isNotNull("o.audit_time");
        q.isNotNull("o.order_type");
        q.orderByDesc( "o.audit_time");
        IPage mapIPage = baseMapper.exchangeReport(page, q);
        return mapIPage;
    }

    @Override
    public IPage<StorageExchangeReport2Vo> exchangeReport2(String orderSn, String userInfo, String agentName, String customerName, String goodsSn, String shipperName, Integer orderType, String actName,
                                                          Integer orderStatus,Integer sysTag,String auditStartTime,String auditEndTime,String receiveStartTime,String receiveEndTime, Page page) {
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("o.order_sn orderSn,o.agent_name agentName,o.id orderId,o.customer_name customerName,o.shipper_name shipperName,o.act_name actName" +
                ", o.created_time createdTime,o.audit_time auditTime,o.ship_time shipTime,o.order_type orderType,o.order_status orderStatus,o.sys_tag sysTag" +
                ",afterSale.receive_time receiveTime,afterSale.id afterSaleId"+
                " ,goods.goods_sn goodsSn,goods.sku_desp skuDesp,goods.chag_sku_desp chagSkuDesp,goods.goods_img,goods.cat_name"+
                " ,address.contact_user contactUser,address.contact_phone contactPhone");
        q.like(StrUtil.isNotEmpty(orderSn),"o.order_sn",orderSn);
        q.and(StrUtil.isNotEmpty(userInfo),i->i.like("address.contact_user",userInfo).or().like("address.contact_phone",userInfo));
        q.like(StrUtil.isNotEmpty(agentName),"o.agent_name",agentName);
        q.like(StrUtil.isNotEmpty(customerName),"o.customer_name",customerName);
        q.like(StrUtil.isNotEmpty(goodsSn),"goods.goods_sn",goodsSn);
        q.like(StrUtil.isNotEmpty(shipperName),"o.shipper_name",shipperName);
        q.eq(orderType!=null,"o.order_type",orderType);
        q.isNotNull("o.order_type");
        q.like(StrUtil.isNotEmpty(actName),"o.act_name",actName);
        q.eq(orderStatus!=null,"o.order_status",orderStatus);
        q.eq(sysTag!=null,"o.sys_tag",sysTag);
        q.eq("afterSale.after_sale_type",AfterSalesTypeEnum.EXCHANE_GOODS.getValue());
        q.ge(StrUtil.isNotEmpty(auditStartTime),"date_format(o.audit_time,'%Y-%m-%d')",auditStartTime);
        q.le(StrUtil.isNotEmpty(auditEndTime),"date_format(o.audit_time,'%Y-%m-%d')",auditEndTime);
        q.ge(StrUtil.isNotEmpty(receiveStartTime),"date_format(o.receive_time,'%Y-%m-%d')",receiveStartTime);
        q.le(StrUtil.isNotEmpty(receiveEndTime),"date_format(o.receive_time,'%Y-%m-%d')",receiveEndTime);
        q.orderByDesc( "afterSale.receive_time");
        IPage mapIPage = baseMapper.exchangeReport2(page, q);
        return mapIPage;
    }

    @Override
    public IPage<StorageRegularReturnVo> regularReturnReport(Integer roleType, Long agentId, String goodsSn, String userName,Integer orderType,Long actId, Long catId, String buyer, String orderSn, String mobile, String startTime, String endTime,String receiveRemark, Page page) {
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("o.order_sn orderSn,o.out_trade_no outTradeNo,o.buyer,goods.goods_img goodsImg,goods.goods_name goodsName,goods.style_no styleNo" +
                ",o.order_from,distributor.agent_name distributorName,o.act_name" +
                ",goods.goods_sn goodsSn,goods.sku_desp skuDesp,goods.color,product.cat_name catName,goods.quantity" +
                ",product.goods_sys," +
                /*" stock.storehouse" +*/
                " oas.depot_location storehouse,oas.receive_remark" +
                ",goods.size,goods.height,goods.weight,goods.price,agent.agent_discount*o.order_price discountPrice,agent.agent_discount discount,o.depot_name depotName,o.express_sn expressSn,o.express_name" +
                ",o.agent_name agentName,o.customer_name customerName,o.shipper_name shipperName,o.remark,address.contact_user contactUser" +
                ",address.contact_phone contactPhone,CONCAT_WS('',address.province,address.city,address.region,address.town,address.addr_detail) address" +
                ",o.ship_time,o.audit_time,o.order_type");
        q.eq("log.log_type", OrderLogTypeEnum.REFUND.getValue());
        q.and(roleType!=null,i->i.eq("agent.agent_id",agentId).eq("agent.role_type",roleType));
        q.eq(roleType==null,"agent.role_type",1);
        q.ne("agent.belong_type",GlobalConstant.PROFIT_BELONG_TYPE_PARTNER);
        q.eq(orderType!=null,"o.order_type", orderType);
        q.isNotNull("o.order_type");
        q.eq(actId!=null,"o.act_id", actId);
        q.like(StrUtil.isNotEmpty(goodsSn),"goods.goods_sn",goodsSn);
        q.like(StrUtil.isNotEmpty(userName),"address.contact_user",userName);
        q.eq(catId!=null,"product.cat_id",catId);
        q.like(StrUtil.isNotEmpty(orderSn),"o.order_sn",orderSn);
        q.like(StrUtil.isNotEmpty(buyer),"o.buyer",buyer);
        q.like(StrUtil.isNotEmpty(mobile),"address.contact_phone",mobile);
        q.ge(StrUtil.isNotEmpty(startTime),"date_format(log.created_time,'%Y-%m-%d')",startTime);
        q.le(StrUtil.isNotEmpty(endTime),"date_format(log.created_time,'%Y-%m-%d')",endTime);
        q.like(StrUtil.isNotEmpty(receiveRemark),"oas.receive_remark",receiveRemark);
        q.orderByDesc( "log.created_time");
        return baseMapper.regularReturnReport(page, q);
    }

    @Override
    public IPage<StorageRegularReturnVo> regularReturnReport2(Integer roleType, Long agentId, String goodsSn, String userName,Integer orderType,Long actId, Long catId, String buyer, String orderSn, String mobile, String startTime, String endTime,String receiveRemark,Integer findState, Page page) {
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("o.order_sn orderSn,o.out_trade_no outTradeNo,o.buyer,goods.goods_img goodsImg,goods.goods_name goodsName,goods.style_no styleNo" +
                ",o.order_from,distributor.agent_name distributorName,o.act_name" +
                ",goods.goods_sn goodsSn,goods.sku_desp skuDesp,goods.color,product.cat_name catName,goods.quantity" +
                ",product.goods_sys" +
                ",product.discount_price goodsPrice" +
                ",oas.depot_location storehouse,oas.receive_remark,oas.receive_time,oas.check_time,oas.depot_sn,oas.depot_order" +
                ",agent.agent_discount*o.order_price discountPrice" +
                ",goods.size,goods.height,goods.weight,goods.price,goods.market_price,agent.agent_discount discount,o.depot_name depotName,o.express_sn expressSn,o.express_name" +
                ",o.agent_name agentName,o.customer_name customerName,o.shipper_name shipperName,o.remark,address.contact_user contactUser" +
                ",address.contact_phone contactPhone,CONCAT_WS('',address.province,address.city,address.region,address.town,address.addr_detail) address" +
                ",o.ship_time,o.audit_time,o.order_type,o.depot_id,goods.product_id" +
                /*",(SELECT GROUP_CONCAT( wde.depotSn ) FROM wms_depot_extra wde WHERE wde.depot_id = o.depot_id AND wde.product_id= goods.product_id ) depotSnStr" +*/
                "");
        q.eq("oas.after_sale_type", AfterSalesTypeEnum.RETURN_GOODS.getValue());
        if(findState == 1){
            q.eq("oas.receive_tag", 1).isNull("oas.audited_time").isNull("oas.after_sale_result");//只查询已接收
            q.ge(StrUtil.isNotEmpty(startTime),"date_format(oas.receive_time,'%Y-%m-%d')",startTime);
            q.le(StrUtil.isNotEmpty(endTime),"date_format(oas.receive_time,'%Y-%m-%d')",endTime);
        }else if(findState == 2){
            q.isNotNull("oas.audited_time").isNull("oas.after_sale_result");//只查询已审核 审核时候不为空的
            q.ge(StrUtil.isNotEmpty(startTime),"date_format(oas.audited_time,'%Y-%m-%d')",startTime);
            q.le(StrUtil.isNotEmpty(endTime),"date_format(oas.audited_time,'%Y-%m-%d')",endTime);
        }else if(findState == 3){
            q.isNotNull("oas.after_sale_result");//已质检 质检结果不为空的
            q.ge(StrUtil.isNotEmpty(startTime),"date_format(oas.check_time,'%Y-%m-%d')",startTime);
            q.le(StrUtil.isNotEmpty(endTime),"date_format(oas.check_time,'%Y-%m-%d')",endTime);
        }else{
            q.ge(StrUtil.isNotEmpty(startTime),"date_format(oas.created_time,'%Y-%m-%d')",startTime);
            q.le(StrUtil.isNotEmpty(endTime),"date_format(oas.created_time,'%Y-%m-%d')",endTime);
        }
        q.and(roleType!=null,i->i.eq("agent.agent_id",agentId).eq("agent.role_type",roleType));
        q.eq(roleType==null,"agent.role_type",1);
        q.ne("agent.belong_type",GlobalConstant.PROFIT_BELONG_TYPE_PARTNER);
        q.eq(orderType!=null,"o.order_type", orderType);
        q.isNotNull("o.order_type");
        q.eq(actId!=null,"o.act_id", actId);
        q.like(StrUtil.isNotEmpty(goodsSn),"goods.goods_sn",goodsSn);
        q.like(StrUtil.isNotEmpty(userName),"address.contact_user",userName);
        q.eq(catId!=null,"product.cat_id",catId);
        q.like(StrUtil.isNotEmpty(orderSn),"o.order_sn",orderSn);
        q.like(StrUtil.isNotEmpty(buyer),"o.buyer",buyer);
        q.like(StrUtil.isNotEmpty(mobile),"address.contact_phone",mobile);
        q.like(StrUtil.isNotEmpty(receiveRemark),"oas.receive_remark",receiveRemark);
        q.orderByDesc( "oas.created_time");
        return baseMapper.regularReturnReport2(page, q);
    }

    @Override
    public IPage<StorageOutAndInReportVo> outAndInReport(Integer billType, Long catId, String goodsSn, String styleNo, String startTime, String endTime, String sortField, String sortType, Page page) {
        return baseMapper.outAndInReport(page,billType,catId,goodsSn,styleNo,startTime,endTime,sortField,sortType);
    }

    @Override
    public IPage<StorageDefectReportVo> defectReport(Integer roleType,Long customerId, Long agentId, String startTime, String endTime, String sortField, String sortType, Page page) {
        QueryWrapper<Order> q = new QueryWrapper<>();

        String select="";
        if (roleType==null){
            select="o.customer_id customerId,o.customer_name customerName,agent.agent_id agentId,agent.agent_name userName,1 as roleType,agent.agent_discount agentDiscount,'客服' as userRole";
            q.eq("agent.role_type",1);
            q.groupBy("agent.agent_id","agent.role_type");
        }else{
            select="o.customer_id customerId,o.customer_name customerName,agent.agent_id agentId,agent.agent_name userName,2 as roleType,agent.agent_discount agentDiscount" +
                    ",case agent.agent_level when "+AgentLevelEnum.DEALER.getValue()+" then '"+AgentLevelEnum.DEALER.getDesp()+"' " +
                    "when "+AgentLevelEnum.LEVEL_1.getValue()+" then '"+AgentLevelEnum.LEVEL_1.getDesp()+"' " +
                    "when "+AgentLevelEnum.LEVEL_2.getValue()+" then '"+AgentLevelEnum.LEVEL_2.getDesp()+"' " +
                    "when "+AgentLevelEnum.LEVEL_3.getValue()+" then '"+AgentLevelEnum.LEVEL_3.getDesp()+"' " +
                    "when "+AgentLevelEnum.LEVEL_4.getValue()+" then '"+AgentLevelEnum.LEVEL_4.getDesp()+"' " +
                    "when "+AgentLevelEnum.LEVEL_5.getValue()+" then '"+AgentLevelEnum.LEVEL_5.getDesp()+"' else '' end userRole";
            q.eq("agent.agent_id",agentId);
            q.eq("agent.role_type",roleType);
            q.groupBy("agent.agent_id","agent.role_type");
        }
        q.select(select +
                ",count(if(afterSale.after_sale_result="+AfterSaleResultEnum.IN_DEFE.getValue()+",true,null)) as flawQuantity" +
                ",IFNULL(sum(if(afterSale.after_sale_result="+AfterSaleResultEnum.IN_DEFE.getValue()+",o.order_price,0)),0) as flawAmount" +
                ",count(if(afterSale.after_sale_result="+AfterSaleResultEnum.PROBLEM_ORDER.getValue()+",true,null)) as issueQuantity" +
                ",IFNULL(sum(if(afterSale.after_sale_result="+AfterSaleResultEnum.PROBLEM_ORDER.getValue()+",o.order_price,0)),0) as issueAmount" +
                "");
        //只筛选审核完成的订单
        q.isNotNull("afterSale.check_time");
        //是次品订单或者问题订单
        q.and(i->i.eq("afterSale.after_sale_result",AfterSaleResultEnum.IN_DEFE.getValue()).or().eq("afterSale.after_sale_result",AfterSaleResultEnum.PROBLEM_ORDER.getValue()));
        q.ge(StrUtil.isNotEmpty(startTime),"date_format(afterSale.check_time,'%Y-%m-%d')",startTime);
        q.le(StrUtil.isNotEmpty(endTime),"date_format(afterSale.check_time,'%Y-%m-%d')",endTime);
        //客服筛选
        q.eq(customerId !=null,"o.customer_id",customerId);
        //排序
        q.orderBy(StrUtil.isNotEmpty(sortField), StringUtils.equalsIgnoreCase("ASC", sortType),sortField);
        IPage pageMaps = baseMapper.defectReport(page, q);
        return pageMaps;
    }

    @Override
    public IPage<StorageDefectReportDetailVo> defectReportDetail(String orderSn,Long customerId,Integer roleType, Long agentId, Integer type, String startTime, String endTime,String agentName,String contactUser,String mobile, Page page) {
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("o.order_sn orderSn,goods.style_no styleNo,goods.partition_name partitionName,goods.cat_name catName,goods.goods_sn goodsSn"
                +
                ",goods.price,o.agent_name agentName,o.customer_name customerName,o.distributor_name distributorName,address.contact_user contactUser" +
                ",address.contact_phone contactPhone,CONCAT_WS('',address.province,address.city,address.region,address.town,address.addr_detail) address" +
                ",if(afterSale.after_sale_result="+AfterSaleResultEnum.IN_DEFE.getValue() +",'是','否') flaw,if(afterSale.after_sale_result="
                +AfterSaleResultEnum.PROBLEM_ORDER.getValue() +",'是','否') issue" +
                ",o.ship_time,afterSale.check_time");
        q.eq(agentId!=null,"agent.agent_id",agentId);
        q.eq(roleType!=null,"agent.role_type",roleType);
        //q.eq("afterSale.after_sale_type",AfterSalesTypeEnum.RETURN_GOODS.getValue());
        //客服ID
        q.eq(customerId!=null,"o.customer_id",customerId);
        //订单编号
        q.like(StrUtil.isNotEmpty(orderSn),"o.order_sn",orderSn);

        //是次品订单或者问题订单
        q.and(i->i.eq("afterSale.after_sale_result",AfterSaleResultEnum.IN_DEFE.getValue()).or().eq("afterSale.after_sale_result",AfterSaleResultEnum.PROBLEM_ORDER.getValue()));
        q.eq(type!=null&&type==1,"afterSale.after_sale_result",AfterSaleResultEnum.IN_DEFE.getValue());
        q.eq(type!=null&&type==2,"afterSale.after_sale_result",AfterSaleResultEnum.PROBLEM_ORDER.getValue());
        q.ge(StrUtil.isNotEmpty(startTime),"date_format(afterSale.check_time,'%Y-%m-%d')",startTime);
        q.le(StrUtil.isNotEmpty(endTime),"date_format(afterSale.check_time,'%Y-%m-%d')",endTime);
        q.like(StrUtil.isNotEmpty(agentName),"o.agent_name",agentName);
        q.like(StrUtil.isNotEmpty(contactUser),"address.contact_user",contactUser);
        q.like(StrUtil.isNotEmpty(mobile),"address.contact_phone",mobile);
        //只筛选审核完成的订单
        q.isNotNull("afterSale.check_time");
        q.orderByDesc( "afterSale.check_time");
        IPage mapIPage = null;
        if(agentId != null && roleType!=null){
            mapIPage = baseMapper.defectReportDetail(page, q);
        }else{
            mapIPage = baseMapper.defectReportDetail2(page, q);
        }

        return mapIPage;
    }

    @Override
    public IPage<StorageInterceptVo> storageIntercept(Integer orderType, Integer agentType,Long actId, String startTime, String endTime, String sortField, String sortType, Page page) {
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("o.order_type,o.customer_id,o.customer_name,date_format(o.audit_time,'%Y-%m-%d') date,agent.agent_type,count(0) quantity,sum(o.order_price) amount");
        q.eq(orderType!=null,"o.order_type",orderType);
        q.eq(agentType!=null,"agent.agent_type",agentType);
        //只筛选审核完成的订单
        q.isNotNull("o.audit_time");
        //指定未发货状态的订单
        q.eq("o.front_order_status",OrderFrontStateEnum.WAIT_SHIP.getValue());
        //取消、断货、和退货的不算
        q.ne("o.sys_tag",OrderSysTagEnum.YTHC_TAG_505.getValue());
        q.ne("o.sys_tag",OrderSysTagEnum.DHF_TAG_306.getValue());
        q.ne("o.sys_tag",OrderSysTagEnum.QXF_TAG_307.getValue());

        q.ge(StrUtil.isNotEmpty(startTime),"date_format(o.audit_time,'%Y-%m-%d')",startTime);
        q.le(StrUtil.isNotEmpty(endTime),"date_format(o.audit_time,'%Y-%m-%d')",endTime);
        //只统计经销商自己和团队的订单
        q.eq("agent.agent_level",AgentLevelEnum.DEALER.getValue());
        q.and(i->i.eq("agent.belong_type", 1).or().eq("agent.belong_type",2));
        //活动筛选
        q.eq(actId!=null,"o.act_id",actId);
        //排序
        q.orderBy(StrUtil.isNotEmpty(sortField), StringUtils.equalsIgnoreCase("ASC", sortType),sortField);
        q.groupBy("date_format(o.audit_time,'%Y-%m-%d')","o.customer_id","agent.agent_type","o.order_type");
        return baseMapper.storageIntercept(page,q);
    }

    @Override
    public IPage<StorageInterceptDetailVo> storageInterceptDetail(Long customerId, Integer orderType, Integer agentType, String startTime, String endTime, Page page) {
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("o.order_sn,goods.goods_img,goods.goods_name,goods.goods_sn,goods.style_no,goods.color,goods.size,o.shipper_name,express.contact_user" +
                ",express.contact_phone,o.order_type,o.order_status,o.agent_name,agent.agent_name distributorName,o.buyer,o.audit_time,goods.price");
        q.eq(customerId!=null,"o.customer_id",customerId);
        q.eq(orderType!=null,"o.order_type",orderType);
        q.eq(agentType!=null,"agent.agent_type",agentType);
        //取消、断货、和退货的不算
        q.ne("o.sys_tag",OrderSysTagEnum.YTHC_TAG_505.getValue());
        q.ne("o.sys_tag",OrderSysTagEnum.DHF_TAG_306.getValue());
        q.ne("o.sys_tag",OrderSysTagEnum.QXF_TAG_307.getValue());
        //只统计经销商自己和团队的订单
        q.eq("agent.agent_level",AgentLevelEnum.DEALER.getValue());
        q.and(i->i.eq("agent.belong_type", 1).or().eq("agent.belong_type",2));
        //只筛选审核完成的订单
        q.isNotNull("o.audit_time");
        //指定未发货状态的订单
        q.eq("o.front_order_status",OrderFrontStateEnum.WAIT_SHIP.getValue());
        q.ge(StrUtil.isNotEmpty(startTime),"date_format(o.audit_time,'%Y-%m-%d')",startTime);
        q.le(StrUtil.isNotEmpty(endTime),"date_format(o.audit_time,'%Y-%m-%d')",endTime);
        return baseMapper.storageInterceptDetail(page,q);
    }

    @Override
    public List<ActivityVo> activityList(Integer type) {
        QueryWrapper<Order> q = new QueryWrapper<>();
        q.select("act.id actId,act.act_name");
        q.eq(type!=null,"act.act_type",type);
        List<ActivityVo> list = baseMapper.activityList(q);
        return list;
    }
}
